package com.balance.anole.client.retail.service.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.balance.anole.business.to.BusinessDateTO;
import com.balance.anole.client.retail.dao.DataTransferDAO;
import com.balance.anole.client.retail.dao.MySQLExportDAO;
import com.balance.anole.client.retail.service.UploadDownloadService;
import com.balance.anole.upload.to.TransferedTableTO;
import com.balance.anole.utils.DateUtil;
import com.balance.anole.utils.UploadDownloadUtil;

public class UploadDownloadServiceImpl implements UploadDownloadService {

	private static final Logger logger = Logger.getLogger(UploadDownloadServiceImpl.class);

	private UploadDownloadUtil udu = UploadDownloadUtil.getInstance();
	private MySQLExportDAO mySQLExportDAO;

	private DataTransferDAO dataTransferDAO;

	public void cleanPreviousExportedData(BusinessDateTO businessDate){

	}

	private void cleanOldFile(File file){
		if(file != null && file.exists()){
			file.delete();
		}
	}

	@Override
	public boolean upload(BusinessDateTO businessDate, String agentId) {

		if(businessDate == null){
			throw new RuntimeException("Business date is not valid.");
		}

		boolean result = true;
		try {
			/*FtpUtil ftp = new FtpUtil();
			String server = udu.getConfigValueByKey("FTP.SERVER");
			String port = udu.getConfigValueByKey("FTP.PORT");
			String username = udu.getConfigValueByKey("FTP.USERNAME");
			String password = udu.getConfigValueByKey("FTP.PASSWORD");
			String path = udu.getConfigValueByKey("FTP.FOLDER");
			ftp.connectServer(server, Integer.parseInt(port), username, password, path);*/

			List<TransferedTableTO> tables = dataTransferDAO.getTablesForTransfer();
			for (TransferedTableTO table : tables) {
				result &= exportData(businessDate, agentId, table);
				if(!result){
					break;
				}
//				ftp.uploadFile(udu.getBodyFileFullPathByTable(businessDate, agentId, tableName), udu.getBodyFileShortNameTable(tableName));
			}

//			ftp.closeServer();
		/*} catch (IOException e) {
			logger.error(e);
			throw new RuntimeException("数据上传服务器失败，请检查ftp服务器是否正常.");*/
		} catch (Exception e) {
			logger.error(e);
			throw new RuntimeException(e.getMessage());
		}

		return result;
	}

	private boolean exportData(BusinessDateTO businessDate, String agentId, TransferedTableTO table) {
		Date currentBizDate = businessDate.getBusinessDate();
		String currentBizDateStr = DateUtil.format(currentBizDate, "yyyy/MM/dd");
		String countQuery = table.getCountQuery();
		int expectedCount = mySQLExportDAO.expectedExportLineNumber(countQuery, businessDate.getBusinessDate(), agentId);
		String fileName = udu.getFileFullPath(businessDate, agentId, table.getBodyFileName());
		String headerFileName = udu.getFileFullPath(businessDate, agentId, table.getHeaderFileName());
		String exportQuery = table.getExportQuery().replace("${fileName}", fileName).replace("${businessDate}", "str_to_date('" + currentBizDateStr + "', '%Y/%m/%d')");

		if(expectedCount > 0){
			File exportedFile = new File(fileName);
			File headerFile = new File(headerFileName);
			//remove existing file with the same name.
			cleanOldFile(exportedFile);
			cleanOldFile(headerFile);

			//write header file
			BufferedWriter bw = null;
			try {
				bw = new BufferedWriter(new FileWriter(headerFile));
				bw.write("BUSINESS_DATE:" + DateUtil.format(businessDate.getBusinessDate(), "yyyyMMdd"));
				bw.newLine();
				bw.write("TABLE_NAME:" + table.getTableName().toUpperCase());
				bw.newLine();
				bw.write("LINE_COUNT:" + expectedCount);
			} catch (IOException e1) {
				logger.error("Error while writting header file " + fileName + " for " + table, e1);
				throw new RuntimeException(fileName + " 头文件写入错误");
			}finally{
				if(bw != null){
					try {
						bw.close();
					} catch (IOException e) {
						logger.error(e);
					}
				}
			}

			//export file using Mysql query.
			mySQLExportDAO.exportDataUsingQuery(exportQuery);


			//validating the exported data.
			int lines = -1;//regardless the header.
			if(exportedFile.exists()){
				FileReader fr = null;
				BufferedReader reader = null;
				try {
					fr = new FileReader(fileName);
					reader = new BufferedReader(fr);
					while (reader.readLine() != null) lines++;
				}catch(Exception e){
					logger.error("Error while validating the exported data file: " + fileName, e);
					throw new RuntimeException(fileName + " 导出文件验证错误");
				}finally{
					try {
						if (fr != null) {
							fr.close();
						}
						if (reader != null) {
							reader.close();
						}
					} catch (IOException e) {
						logger.error(e);
					}
				}
			}

			if(! exportedFile.exists() || lines != expectedCount){
				return false;
			}
		}else{
			throw new RuntimeException(table.getTableName() + " 没有数据");
		}

		return true;

	}
	public MySQLExportDAO getMySQLExportDAO() {
		return mySQLExportDAO;
	}
	public void setMySQLExportDAO(MySQLExportDAO mySQLExportDAO) {
		this.mySQLExportDAO = mySQLExportDAO;
	}

	public DataTransferDAO getDataTransferDAO() {
		return dataTransferDAO;
	}

	public void setDataTransferDAO(DataTransferDAO dataTransferDAO) {
		this.dataTransferDAO = dataTransferDAO;
	}
}
